package com.xiyu.service.dal.job;


import com.xiyu.service.framework.job.core.handler.JobHandler;
import com.xiyu.service.framework.postOffice.factory.PostOfficeFactory;
import com.xiyu.service.framework.postOffice.service.PostOfficeService;
import com.xiyu.service.model.mailbox.account.MailboxAccount;
import com.xiyu.service.model.mailbox.mail.MailboxMailErrorLogDraft;
import com.xiyu.service.repository.mailbox.account.MailboxAccountRepository;
import com.xiyu.service.service.mailbox.MailboxMailErrorLogService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
@DisallowConcurrentExecution
public class ReceiveMailJob implements JobHandler {

    @Resource
    MailboxAccountRepository mailboxAccountRepository;

    @Resource
    PostOfficeFactory postOfficeFactory;

    @Resource
    MailboxMailErrorLogService mailboxMailErrorLogService;

    @Override
    public String execute(String param) {
        List<MailboxAccount> accounts = mailboxAccountRepository.findAll();
        log.info("开始收取邮件");
        for (MailboxAccount account : accounts){
            if(account.lastReceiveTime() == null)
                continue;
            long minutes = Duration.between(account.lastReceiveTime(), LocalDateTime.now()).toMinutes();
            if(minutes >= account.timeReceiveInterval()){
                try{
                    PostOfficeService postOfficeService = postOfficeFactory.getInstance(account.id());
                    postOfficeService.receiveAccountMailJob();
                }catch (Exception e){
                    mailboxMailErrorLogService.saveMailErrorInfo(account.id(), 0L, 0L, "", e);
                }
            }
        }
        log.info("结束收取邮件");
        return "" ;
    }
}
